package config

import (
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
)

type Config struct {
	System struct {
		Port              string `yaml:"port"`
		ApiPrefix         string `yaml:"apiPrefix"`
		TempPath          string `yaml:"tempPath"`
		TempCleanInterval int    `yaml:"tempCleanInterval"` // 临时文件清理时间间隔单位分钟
		LibreOffice       string `yaml:"libreOffice"`
		Ffprobe           string `yaml:"ffprobe"`
		PhoneDat          string `yaml:"phoneDat"`
		IpDat             string `yaml:"ipDat"`
	}
	// static file server
	Sfs struct {
		Url     string `yaml:"url"`
		Path    string `yaml:"path"`
		Preview bool   `yaml:"preview"`
	}
	Minio struct {
		Endpoint   string `yaml:"endpoint"`
		AccessKey  string `yaml:"accessKey"`
		SecretKey  string `yaml:"secretKey"`
		Secure     bool   `yaml:"secure"`
		BucketName string `yaml:"bucketName"`
	}
	Nacos struct {
		ClientIp      string        `yaml:"clientIp"`           //required
		Weight        float64       `yaml:"weight"`             //required,it must be lager than 0
		ClusterName   string        `yaml:"clusterName"`        //optional,default:DEFAULT
		ServiceName   string        `yaml:"serviceName"`        //required
		GroupName     string        `yaml:"groupName"`          //optional,default:DEFAULT_GROUP
		TimeoutMs     uint64        `yaml:"timeoutMs"`          //optional
		LogLevel      string        `yaml:"logLevel"`           //optional
		LogDir        string        `yaml:"logDir"`             //optional
		CacheDir      string        `yaml:"cacheDir"`           //optional
		ServerConfigs []NacosServer `yaml:"serverConfigs,flow"` //required
	}
}

type NacosServer struct {
	Scheme      string `yaml:"scheme"`
	ContextPath string `yaml:"contextPath"`
	IpAddr      string `yaml:"ipAddr"`
	Port        uint64 `yaml:"port"`
}

func Init() Config {
	var cfg Config
	dir, err := os.Getwd()
	if err == nil {
		err = unmarshal(dir+"/config.yaml", &cfg)
	}
	if err != nil {
		panic(err)
	}
	// 临时文件存放目录初始化，默认当前目录 temp 文件夹
	var tempPath = cfg.System.TempPath
	if len(tempPath) < 1 {
		tempPath = path.Join(dir, "temp")
	} else {
		tempPath, _ = filepath.Abs(tempPath)
	}
	_, err = os.Stat(tempPath)
	if os.IsNotExist(err) {
		// 文件夹不存在初始化
		err := os.MkdirAll(tempPath, 0766)
		if err != nil {
			panic(err)
		}
	}
	// 回写临时路径
	cfg.System.TempPath = tempPath
	return cfg
}

func unmarshal(filename string, out interface{}) error {
	data, err := ioutil.ReadFile(filename)
	if err == nil {
		err = yaml.Unmarshal(data, out)
	}
	return err
}
